package com.infinit.easyreader.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.infinit.easyreader.Biz.BookBiz;
import com.infinit.easyreader.R;
import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.fragment.BooksFragment;
import com.infinit.easyreader.fragment.CloudFragment;
import com.infinit.easyreader.fragment.CollectionFragment;
import com.infinit.easyreader.fragment.SettingsFragment;
import com.infinit.easyreader.utils.FindBookType;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class HomeActivity extends AppCompatActivity {
    @Bind(R.id.tab_books)
    RelativeLayout tabBooks;
    @Bind(R.id.tvBooks)
    TextView tvBooks;
    @Bind(R.id.tab_collections)
    RelativeLayout tabCollections;
    @Bind(R.id.tvCollections)
    TextView tvCollections;
    @Bind(R.id.tab_cloud)
    RelativeLayout tabCloud;
    @Bind(R.id.tvCloud)
    TextView tvCloud;
    @Bind(R.id.tab_settings)
    RelativeLayout tabSettings;
    @Bind(R.id.tvSettings)
    TextView tvSettings;
    @Bind(R.id.rbEditCollect)
    RadioButton rbEditCollect;
    @Bind(R.id.rbEditDelete)
    RadioButton rbEditDelete;
    @Bind(R.id.rbEditUpload)
    RadioButton rbEditUpload;
    @Bind(R.id.rbEditCancel)
    RadioButton rbEditCancel;
    @Bind(R.id.rgEditBar)
    RadioGroup rgEditBar;
    @Bind(R.id.footer)
    LinearLayout footer;
    @Bind(R.id.btBooks)
    Button btBooks;
    @Bind(R.id.btCollections)
    Button btCollections;
    @Bind(R.id.btCloud)
    Button btCloud;
    @Bind(R.id.btSettings)
    Button btSettings;
    private List<android.support.v4.app.Fragment> fragments;
    private int showingIndex = 0;
    private Book currentBook;
    private BookBiz currentBookBiz;
    private FindBookType type;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        //将所有Fragment实例化
        genAllFragments();
        setListener();
        //显示第一个Fragment
        switchFragment(0);
    }

    /**
     * 设置当前操作的数据源和操作的书籍
     *
     * @param book 需要操作的书籍
     */

    public void setCurrentStatus(Book book, BookBiz bookBiz, FindBookType type) {
        this.currentBookBiz = bookBiz;
        this.currentBook = book;
        this.type = type;
    }


    /**
     * 作用：生成所有的Fragment并且将其加入到List中。
     */
    private void genAllFragments() {
        fragments = new ArrayList<>();
        BooksFragment booksFragment = new BooksFragment();
        CloudFragment cloudFragment = new CloudFragment();
        CollectionFragment collectionFragment = new CollectionFragment();
        SettingsFragment settingsFragment = new SettingsFragment();
        fragments.add(booksFragment);
        fragments.add(collectionFragment);
        fragments.add(cloudFragment);
        fragments.add(settingsFragment);
    }

    /**
     * 作用：切换需要显示的Fragment
     *
     * @param need2ShowIndex 当前需要显示的Fragment的index
     */
    private void switchFragment(int need2ShowIndex) {
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        android.support.v4.app.Fragment need2ShowFragment = fragments.get(need2ShowIndex);
        //判断该Fragment是否已经被添加
        if (!fragments.get(need2ShowIndex).isAdded()) {
            fragmentTransaction.add(R.id.flFragment, need2ShowFragment);
        }
        fragmentTransaction.hide(fragments.get(showingIndex));
        if (need2ShowFragment.isHidden()) {
            if (need2ShowFragment instanceof CollectionFragment) {
                ((CollectionFragment) need2ShowFragment).updateData();
            } else if (need2ShowFragment instanceof BooksFragment) {
                //更新数据
                ((BooksFragment) fragments.get(0)).updateData();
            }
        }
        fragmentTransaction.show(need2ShowFragment);
        fragmentTransaction.commit();
        showingIndex = need2ShowIndex;
    }


    /**
     * Callback
     * 为所有按钮绑定点击事件
     *
     * @param view View对象
     */

    @OnClick({R.id.tab_books, R.id.tab_cloud, R.id.tab_collections, R.id.tab_settings})
    public void clickTab(View view) {
        switch (view.getId()) {
            case R.id.tab_books:
                selectButton(btBooks, tvBooks);
                switchFragment(0);
                break;
            case R.id.tab_collections:
                selectButton(btCollections, tvCollections);
                switchFragment(1);
                //更新数据
//                ((CollectionFragment) fragments.get(1)).updateData();
                break;
            case R.id.tab_cloud:
                selectButton(btCloud, tvCloud);
                switchFragment(2);
                break;
            case R.id.tab_settings:
                selectButton(btSettings, tvSettings);
                switchFragment(3);
                break;
        }
    }


    /**
     * 作用：选择指定的Button
     *
     * @param button   指定的button
     * @param textView 指定的TextView
     */

    private void selectButton(Button button, TextView textView) {
        //初始化所有TAB和TextView
        btBooks.setEnabled(true);
        btCloud.setEnabled(true);
        btCollections.setEnabled(true);
        btSettings.setEnabled(true);
        @SuppressWarnings("deprecation") int blackColorId = getResources().getColor(R.color.text_color_black);
        @SuppressWarnings("deprecation") int blueColorId = getResources().getColor(R.color.text_color_tab_seleted);
        tvBooks.setTextColor(blackColorId);
        tvCloud.setTextColor(blackColorId);
        tvCollections.setTextColor(blackColorId);
        tvSettings.setTextColor(blackColorId);
        //设置该按钮的样式
        button.setEnabled(false);
        textView.setTextColor(blueColorId);
    }


    /**
     * 作用：为指定的控件设置监听器
     */
    private void setListener() {
        /**
         * 作用：为删除按钮添加监听器
         */

        rbEditDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除书籍
                //弹出一个提示框，使用来自github的sweetAlertDialogue,详情请参阅
                // https://github.com/pedant/sweet-alert-dialog
                new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("确定删除?")
                        .setContentText("该书籍将从SD卡彻底删除！")
                        .setConfirmText("删除")
                        .setCancelText("取消")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        })
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                //从SD卡删除该文件
                                currentBookBiz.deleteBook(currentBook);
                                currentBookBiz.new FindBooksTask().execute(FindBookType.ALL);
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        })
                        .show();
                //更新显示
                footer.setVisibility(View.VISIBLE);
                rgEditBar.setVisibility(View.GONE);
            }
        });

        /**
         * 作用：为取消按钮添加监听器
         */

        rbEditCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                footer.setVisibility(View.VISIBLE);
                rgEditBar.setVisibility(View.GONE);
            }
        });

        /**
         * 作用：为收藏按钮添加监听器
         */

        rbEditCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收藏
                currentBookBiz.collectBook(currentBook);
                //更新显示
                currentBookBiz.new FindBooksTask().execute(type);
                footer.setVisibility(View.VISIBLE);
                rgEditBar.setVisibility(View.GONE);
            }
        });

        /**
         * 作用：为上传按钮提供监听器
         */
        rbEditUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上传
                footer.setVisibility(View.VISIBLE);
                rgEditBar.setVisibility(View.GONE);
            }
        });


    }

}

